package com.example.crondemo.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crondemo.exception.TaskException;
import com.example.crondemo.model.Stock;
import com.example.crondemo.model.vo.StockQueryVo;
import com.example.crondemo.result.Result;
import com.example.crondemo.result.ResultCodeEnum;
import com.example.crondemo.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yanbl
 * @since 2021-06-30
 */
@RestController
@RequestMapping("/api/stock")
@CrossOrigin
public class StockController {

    @Autowired
    private StockService stockService;

    // 根据条件获取库存数据
    @GetMapping("/list/{page}/{limit}")
    public Result findByVo(
            @PathVariable Integer page,
            @PathVariable Integer limit,
            StockQueryVo stockQueryVo
    ){

        Page<Stock> byCondition;
        try {
            // 根据条件分页查询
            byCondition = stockService.findByCondition(page, limit, stockQueryVo);
        }catch (TaskException taskException) {
            return new Result(ResultCodeEnum.THANONEMOUTH);
        }

        return Result.ok(byCondition);
    }

    /**
     * 根据起止时间查询接口中的库存数据
     * 并且添加到数据库中
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("/saveStock/{startTime}/{endTime}")
    public Result findStocksByInvoke(@PathVariable String startTime,@PathVariable String endTime) {
        // 查询出来数据
        List<Stock> stockInvoke = stockService.findStockInvoke(startTime, endTime);

        // 添加到或修改到数据库
        stockService.addStocks(stockInvoke);
        return Result.ok(stockInvoke);

    }

}
